/*
 *  This file is part of Bracket Properties
 *  Copyright 2011 David R. Smith
 *
 */
package org.dave.bracket.properties;

import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
/**
 * Format properties into xml. The default namespace is http://code.google.com/p/bracket-properties
 *  
 * @author Dave
 *
 */
public class GenerateXMLNodeVisitor implements NodeVisitor {
	
	final String NS = "xmlns=\"http://code.google.com/p/bracket-properties\"";
	final Writer writer;
	int level;
	final HashSet<Node> set = new HashSet<Node>();
	
	public GenerateXMLNodeVisitor(Writer writer) {
		super();
		this.writer = writer;
	}

	public void pre(Node node) {
		if(!set.contains(node)){
			set.add(node);
			level++;
		}
		try {
			writer.append(spaces());
			writer.append("<");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void action(Node node) {
		try {
			writer.append(node.getName());
			if(level == 1){
				writer.append(" ");
				writer.append(NS);
			}
			writer.append(">");
			writer.append(System.lineSeparator());
			if(node.hasValue()){
				writer.append(node.getValue().toXML(level));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void post(Node node) {
		if(set.contains(node)){
			set.add(node);
			level--;
		}
		try {
			writer.append(spaces());
			writer.append("</").append(node.getName()).append(">").append("\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void setLevel(int level) {
		this.level = level;
	}

	private String spaces(){
		StringBuilder sp = new StringBuilder();
		for(int i=0;i<level;i++)sp.append(" ");
		return sp.toString();
	}
}
